import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 订单数据
const orderData = ref([])

// 分页配置
const orderPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 筛选条件
const orderFilters = reactive({
  dateRange: 'all',
  search: ''
})

// 从Chrome存储中获取订单数据
const fetchOrderData = async () => {
  return new Promise<any[]>((resolve) => {
    chrome.storage.local.get(['capturedRequests'], (result) => {
      const allRequests = Array.isArray(result.capturedRequests) ? result.capturedRequests : []
      
      // 筛选出订单数据（根据URL或数据类型）
      const orderRequests = allRequests.filter(request => {
        // 根据拦截规则匹配订单数据
        return request.url && (
          request.url.includes('order') || 
          request.url.includes('trade') ||
          (request.dataType && (request.dataType === 'sales_order' || request.dataType === 'purchase_order'))
        )
      })
      
      // 处理数据格式
      const formattedData = orderRequests.map((request: any, index) => {
        // 提取数据预览
        let preview = '{}'
        try {
          if (request.response) {
            preview = JSON.stringify(request.response, null, 2)
          } else if (request.requestBody) {
            preview = JSON.stringify(request.requestBody, null, 2)
          }
        } catch (e) {
          preview = '{}'
        }
        
        // 截取预览内容
        if (preview.length > 100) {
          preview = preview.substring(0, 100) + '...'
        }
        
        // 确定订单状态和类型
        let status = '处理中'
        if (request.synced) {
          status = '已完成'
        } else if (request.processing) {
          status = '处理中'
        }
        
        // 确定订单类型
        let orderType = '销售订单'
        if (request.dataType === 'purchase_order' || 
            (request.url && request.url.includes('purchase'))) {
          orderType = '采购订单'
        }
        
        return {
          id: request.id || index + 1,
          date: request.timestamp ? new Date(request.timestamp).toLocaleString() : new Date().toLocaleString(),
          source: request.url || '未知来源',
          preview: preview,
          status: status,
          orderType: orderType // 添加订单类型字段
        }
      })
      
      resolve(formattedData)
    })
  })
}

// 渲染订单表格
const renderOrdersTable = async () => {
  try {
    const data: any[] = await fetchOrderData()
    orderPagination.total = data.length
    
    // 分页处理
    const start = (orderPagination.currentPage - 1) * orderPagination.pageSize
    const end = start + orderPagination.pageSize
    orderData.value = data.slice(start, end)
  } catch (error) {
    console.error('获取订单数据失败:', error)
    ElMessage.error('获取订单数据失败')
  }
}

// 订单分页处理
const handleOrderPageChange = (page) => {
  orderPagination.currentPage = page
  renderOrdersTable()
}

// 单条同步订单
const syncSingleOrder = (row) => {
  ElMessage.success(`订单数据(ID: ${row.id})同步成功`)
}

// 删除订单
const deleteOrder = (row) => {
  ElMessageBox.confirm(`确定要删除订单数据(ID: ${row.id})吗？`, '删除数据', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 组件挂载时获取数据
onMounted(() => {
  renderOrdersTable()
})

export function useOrderData() {
  return {
    orderData,
    orderPagination,
    orderFilters,
    renderOrdersTable,
    handleOrderPageChange,
    syncSingleOrder,
    deleteOrder
  }
}